package org.gjw.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author guojunwang
 * @date 2022-05-10 23:55
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {


    /**
     * 注册filter
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){

        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter((servletRequest, servletResponse, filterChain) -> {
            //默认使用默认的数据源
            DataSourceHolder.useDefaultDataSource();
            //从请求参数内获取数据源
            Object dsKey = servletRequest.getParameter("dsKey");
            if( dsKey!=null ){
                //如果指定了数据源，使用指定的数据源
                DataSourceHolder.setDataSourceKey(dsKey.toString());
            }
            filterChain.doFilter(servletRequest,servletResponse);
        });
        bean.setOrder(1);
        bean.addUrlPatterns("/*");
        return bean;
    }

}
